<template>
	<view :id="templateId" class="container">
		<empty
			:src="baseTemplateFileUri + '/image/emptyStatus/common.png'"
			v-if="loaded && !couponList.length"
			desc="没有相关卡券 ~"
		></empty>

		<template v-if="couponList.length">
			<uni-banner :image="baseTemplateFileUri + pageBanner.coupon">
			</uni-banner>
			<view class="coupon-wrap">
				<uni-coupon-col
					v-for="(item, index) in couponList"
					:key="index"
					:coupon="item"
					@click="onClickCoupon(index)"
					:option="getCouponOption(item.mayReceive)"
					:couponType="getCouponType(item.couponType)"
				>
				</uni-coupon-col>
			</view>
		</template>
		<!-- 提示 去登录 弹层 -->
		<!-- <notice
			:visible="notLoginPopByQrcode"
			:showCloseIcon="true"
			@close="closeNotLoginPop"
			:hasBg="true"
			:couponBgFirst="true"
			width="560"
			height="560">
			<template slot="body">
				<view class="coupon-pop-go_login zz-flex zz-jc-c zz-ai-c">
					<button
						:style="themeStyles.btnFullColor"
						class="login-btn"
						type="primary"
						@click="goToLoginQrcode"
					>
						去登录
					</button>
				</view>
			</template>
		</notice> -->
		<!-- 提示弹层-优惠券已抢完 -->
		<notice
			:visible="couponBgFirst"
			:showCloseIcon="true"
			@close="couponBgFirst=false"
			:hasBg="true"
			:couponBgFirst="true"
			width="560"
			height="560">
			<template slot="body">
				<view class="zz-flex zz-jc-c zz-mb28 zz-pt120">
					<view class="coupon-pop-bg_wrap">
						<image class="zz-img-fit" :src="`${baseCommonFileUri}image/coupon_complete_icon.png`"></image>
					</view>
				</view>
				<view class="zz-flex zz-jc-c fs34 lh48 color333">该券被抢完了 看看其他的吧</view>
			</template>
		</notice>
		<!-- 提示弹层-优惠券领取 -->
		<!-- 已经领取 赶紧去使用吧 -->
		<!-- 领取成功 -->
		<notice
			:visible="couponBgSecond"
			:showCloseIcon="true"
			@close="couponBgSecond=false"
			:hasBg="true"
			:couponBgSecond="true"
			width="560"
			height="736">
			<template slot="body">
				<view class="zz-flex zz-ff-cw zz-ai-c zz-pt24 color795133">
					<view class="zz-mb24 fs32 lh44">{{
						clickedCoupon.mayReceive===1?"已经领取 赶紧去使用吧":"领取成功"
					}}</view>
					<view 
						:style="clickedCoupon.couponType=='30'?'flex-direction:row-reverse;':''"
						class="zz-flex zz-ai-c zz-mb12 fs-bold">
						<view class="zz-mt26 fs42 lh48">{{clickedCoupon.couponType=="20"?"¥":"%"}}</view>
						<view class="fs80 lh96">{{clickedCoupon.couponType=="20"?`${clickedCoupon.discounts}`:/\./g.test(String(clickedCoupon.discounts))?clickedCoupon.discounts*10:clickedCoupon.discounts}}</view>
					</view>
					<view class="zz-mb6 fs34 lh48">{{clickedCoupon.couponName}}</view>
					<!-- clickedCoupon.content -->
					<view class="zz-mb80 fs28 lh40">{{clickedCoupon.conditions?`满${ZZaddNumZero(clickedCoupon.conditions)}元可用`:" "}}</view>
				</view>
				<view class="zz-mb20 zz-p_0_40 fs24 lh40 color333">
					<view class="zz-mb12">使用方式：</view>
					<view class="color666">小程序里购买商品结算订单时选择抵扣</view>
					<view class="color666">线下门店结账展示付款码时选择抵扣</view>
				</view>
				<view class="zz-mb44 zz-p_0_40 fs24 lh40 color333">
					<view class="zz-mb12">使用时间：</view>
					<view class="color666">{{clickedCoupon.startTime}} 至 {{clickedCoupon.endTime}}</view>
				</view>
				<view 
					class="zz-flex zz-jc-c zz-pb24 fs28 lh40 colorC7A673"
					@click="navTo('/pages/activity/pages/coupon/myCoupon')">查看我的优惠券</view>
			</template>
		</notice>
		<!-- 测试 -->
		<notice
			:visible="couponTest"
			:showCloseIcon="true"
			@close="couponTest=false"
			width="560"
			height="736">
			<template slot="body">
				<view class="lh40">{{couponTestData}}</view>
			</template>
		</notice>
	</view>
</template>

<script>
const app = getApp();
import { queryCouponList } from "@/lib/api/couponServer/info";

import { 
	recevieCoupon,
	couponInfoDetails  // 获取优惠券详情
 } from "@/lib/api/couponServer/customer";

import { 
	distributorShareDetail //获取分享详情
 } from "@/lib/api/distributorServer/share";

/** components begin */
import empty from "@/components/empty";
import uniLoadMore from "@/components/uniLoadMore/uniLoadMore";
import uniCouponCol from "@/components/coupon/uniCouponCol";
import uniBanner from "@/components/uniBanner";
import notice from "@/components/notice";
/** components end */

// 解析二维码
import { analyzeQr } from "@/lib/analyzeQr";

/** mixins begin */
import couponMixin from "@/mixins/coupon/coupon";
import bannerMixin from "@/mixins/banner";
/** mixins end */
/**  vuex **/
import { mapState, mapMutations } from "vuex";
/**  vuex **/
let currentPage = 1;
export default {
	components: {
		uniCouponCol,
		uniBanner,
		uniLoadMore,
		empty,
		notice
	},

	mixins: [
		bannerMixin, 
		couponMixin
	],

	computed:{
		...mapState("coupon", ["couponsByLogin"])
	},
	data() {
		return {
			couponList: [],
			// 二维码识别进入小程序未登录弹层
			//notLoginPopByQrcode:false,
			//优惠券已抢完弹层
			couponBgFirst:false,
			//优惠券领取弹层
			couponBgSecond:false,
			//点击的优惠券
			clickedCoupon:{},
			// test 
			couponTest: false,
			couponTestData:""
		};
	},

	async onLoad(option) {
		currentPage = 1;
		// 从领券海报识别小程序二维码进入
		let scene = option.scene && decodeURIComponent(option.scene);
		console.log("领券海报二维码携带的参数---",scene);
		//
		/* this.$api.showModal({
			title:"测试获取分享id",
			content:`${scene}`
		}); */
		//
		if ((typeof scene === "string" && scene !== "undefined")) { 
			// 分享id存本地
			uni.setStorageSync('distributorShareIdQrcode', scene);
			//uni.setStorageSync('distributorShareIdQrcode', "b9c6c4eafbd34514b786f726baea5045");
			// 未登录时
			if(!this.hasLogin){
				//this.notLoginPopByQrcode = true;
				app.globalData.openCCByShareQrcode = true;
				this.navTo('/pages/common/pages/login/login');
			}
			// 已登录
			if(this.hasLogin){
				try {
					await this.recevieCouponByShare();
				} catch (error) {
					console.log("分享领券出错---",error);
				}
			}
			return;
		}
		//
		try {
			await analyzeQr(option);
		} catch (error) {
			console.log("error", error);
		}
		this.getCouponList();
	},

	async onShow(){
		// 从登录页面返回
		if(app.globalData.openCCByShareQrcodeFromLogin){
			app.globalData.openCCByShareQrcodeFromLogin = false;
			console.log("登录页已登录=>领券中心---",app.globalData.openCCByShareQrcodeFromLogin);
			try {
				await this.recevieCouponByShare()
			} catch (error) {
				console.log("分享领券出错---",error);
			}
			this.setCouponsByLogin([]);
			return;
		}
		//未登录时--点击领取优惠券
		if(this.couponsByLogin.length){
			try {
				await this.onRecevieCoupon(this.couponsByLogin[0].index);
			} catch (error) {

			}
			this.setCouponsByLogin([]);
		}
	},

	// 上拉加载
	onReachBottom() {
		if (!this.hasLogin) return;
		if (this.loadingType === "loading" || this.loadingType === "more") {
			currentPage++;
			this.getCouponList();
		}
	},

	methods: {
		/*  */
		...mapMutations("coupon", ["setCouponsByLogin"]),
		/* 二维码识别小程序进入领券页面 */
		async recevieCouponByShare(){
			try {
				// 获取分享详情
				const res = await distributorShareDetail({
					distributorShareId: uni.getStorageSync("distributorShareIdQrcode")
				});
				//console.log("获取分享详情---",res);
				// 获取优惠券详情
				const res2 = await couponInfoDetails({
					couponId: res.data.itemId
				});
				//console.log("获取优惠券详情---",res2);
				//
				/* let testResults = [];
				for (const key in res2.data) {
					if (res2.data.hasOwnProperty(key)) {
						testResults.push(`（${key}:${res2.data[key]}）`);
					}
				}
				this.couponTestData = testResults.join("=_=");
				this.couponTest = true; */
				//
				this.clickedCoupon = null;
				this.clickedCoupon = Object.assign({},res2.data);
				// 领取优惠券操作
				const res3 = await recevieCoupon({
					couponId: this.clickedCoupon.couponId
				});
				//console.log("领取优惠券结果---",res3);
				this.clickedCoupon.mayReceive = 0;
				this.couponBgSecond = true;
				currentPage = 1;
				this.getCouponList();
				return Promise.resolve();
			} catch (error) {
				// 领券失败
				this.recevieCouponFail(error);
				// 分享领券失败，从列表领取
				currentPage = 1;
				this.getCouponList();
				return Promise.reject(error);
			}
		},
		/* 领券失败对应提示 */
		recevieCouponFail(error){
			switch(error.resultCode){
				/* case 60003:
					this.couponBgFirst = true;
					break; */
				case 60011:
					this.clickedCoupon.mayReceive = 1;
					this.couponBgSecond = true;
					break;
				/* default:
					this.$api.showModal({
						content:`${error.resultInfo || "领取失败"}`
					});
					break; */
					default:
						this.couponBgFirst = true;
						break;
			}
		},
		/* goToLoginQrcode(){ //跳转至登录页面
			//标识
			app.globalData.CCdistributorShareIdQrcode = true;
			this.notLoginPopByQrcode=false;
			this.navTo('/pages/common/pages/login/login');
		},
		closeNotLoginPop(){ //关闭弹窗
			this.notLoginPopByQrcode=false;
			this.ZZsetTimeout(()=>{
				this.notLoginPopByQrcode=true;
			});
		}, */
		/*  */
		onClickCoupon(index) {
			this.onRecevieCoupon(index);
		},

		// 配置卡券组件option
		getCouponOption(mayReceive) {
			let option = {
				metaRightText: "",
				canUseColor: ""
			};
			let bgImageName = "";
			switch (mayReceive) {
				case 0:
					option.metaRightText = "立即领取";
					option.canUseColor = this.themeStyles.mainColor;
					option.canUseMainColor = this.themeStyles.lightMainColor;
					bgImageName = "_can";
					break;
				case 2:
					option.metaRightText = "已抢完";
					option.showRobbedNone = true;
					option.canUseColor = "";
					break;
				default:
					option.metaRightText = "已领取";
					option.canUseColor = "";
					break;
			}
			// option.bgImage =
			// 	this.baseTemplateFileUri +
			// 	`image/coupon/coupon_bg${bgImageName}.png`;
			//console.log(option);
			return option;
		},

		// 领取优惠券
		async onRecevieCoupon(index) {
			if (!this.hasLogin) {
				//存卡片信息
				this.setCouponsByLogin([
					Object.assign({index},coupon)
				]);
				//
				this.navTo("/pages/common/pages/login/login");
				return;
			}
			let coupon = this.couponList[index];
			this.clickedCoupon = null;
			this.clickedCoupon = Object.assign({},coupon);
			console.log("---this.clickedCoupon---",this.clickedCoupon);
			/*  */
			if(coupon.mayReceive != 0){
				switch(coupon.mayReceive){
					case 1:
						this.clickedCoupon.mayReceive = 1;
						this.couponBgSecond = true;
						break;
					case 2:
						this.couponBgFirst = true;
						break;
				}
				return;
			}
			/*  */

			if (this.receiving) return;

			this.receiving = true;

			const propsData = {
				couponId: coupon.couponId
			};

			try {
				const res = await recevieCoupon(propsData);
				this.$set(coupon, "mayReceive", res.data.mayReceive);
				//uni.showToast({ title: "领取成功" });
				/* if (res.data.mayReceive === 1) {
					this.$set(coupon, "mayReceive", 1);
				} */
				//显示领取成功
				this.clickedCoupon.mayReceive = 0;
				this.couponBgSecond = true;
				this.receiving = false;
				return Promise.resolve();
			} catch (error) {
				console.log("error", error);
				this.receiving = false;
				// 领券失败
				this.recevieCouponFail(error);
				/*  */
				currentPage = 1;
				this.getCouponList();
				return Promise.reject();
			}
		},
		// 
		async getCouponList() {
			const propsData = {
				currentPage
			};
			try {
				const res = await queryCouponList(propsData);
				// this.loaded = true;
				// this.couponList = res.data.list;

				const couponList = res.data.list;
				if (currentPage === 1) {
					this.couponList = couponList;
				} else {
					this.couponList = this.couponList.concat(couponList);
				}
				const noMore = this.couponList.length >= res.data.total;
				this.loadingType = noMore ? "noMore" : "more";
				uni.stopPullDownRefresh();
				this.loaded = true;
				return Promise.resolve();
			} catch (error) {
				console.log("error", error);
				this.$api.showToast(error.resultInfo || "操作失败");
				this.loaded = true;
				return Promise.reject(error);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
@import "@/pages/activity/styles/coupon/couponCenter.scss";
</style>